package br.com.seosoft.timbetaadd.telas;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import br.com.seosoft.timbetaadd.R;
import br.com.seosoft.timbetaadd.R.id;
import br.com.seosoft.timbetaadd.R.layout;
import br.com.seosoft.timbetaadd.R.menu;
import br.com.seosoft.timbetaadd.utils.Conf;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;

public class Login extends SherlockActivity {

	Button btn_login_facebook;

	private UiLifecycleHelper uiHelper;
	private static final List<String> PERMISSIONS_READ = Arrays
			.asList("email","user_location");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(Login.this, callback);
		uiHelper.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		btn_login_facebook = (Button) findViewById(R.id.tela_login_btn_facebook_login);

		updateView();

	}

	/*
	 * (non-Javadoc)** ********************* Ciclo de vida da activy
	 */ 
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		uiHelper.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	// **********************************

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {

		if (state.isOpened()) {
			Log.i(Conf.LOG_CAT_TAG_GERAL, "Logged in...");
			Log.i(Conf.LOG_CAT_TAG_GERAL,
					"Permissions: " + session.getPermissions());
			
			

		} else if (state.isClosed()) {
			Log.i(Conf.LOG_CAT_TAG_GERAL, "Logged out...");
		}
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
			updateView();
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	private void updateView() {
		Session session = Session.getActiveSession();

		if (session.isOpened()) {
			btn_login_facebook.setText("Sair");
			btn_login_facebook.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					onClickLogout();
				}
			});
		} else {

			btn_login_facebook.setText("Entrar");
			btn_login_facebook.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					onClickLogin();
				}
			});
		}
	}

	private void onClickLogin() {
		Session session = Session.getActiveSession();

		
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new Session.OpenRequest(this)
					.setCallback(callback).setPermissions(PERMISSIONS_READ));
			
		} else {
			Session.openActiveSession(this, true, callback);
		}
	}

	private void onClickLogout() {
		Session session = Session.getActiveSession();
		if (!session.isClosed()) {
			session.closeAndClearTokenInformation();
		}
	}

	// ******* INFLAE O MENU ******
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.login, menu);
		return true;
	}
	
	// *************** RECUPERA DADOS FACEBOOK *****
	// *********************************************
	
	private void recuperaDadosFacebook(final Session session) {		
		 // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    // Set the id for the ProfilePictureView
	                    // view that in turn displays the profile picture.
	                 //   profilePictureView.setProfileId(user.getId());
	                    // Set the Textview's text to the user's name.
	                   // userNameView.setText(user.getName());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	}
		 
  

	// GERA HASH KEY PARA FACEBOOK
	public void getHash() {

		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(
					"br.com.seosoft.timbetaadd", PackageManager.GET_SIGNATURES);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (Signature signature : info.signatures) {
			MessageDigest md = null;
			try {
				md = MessageDigest.getInstance("SHA");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			md.update(signature.toByteArray());
			Log.d(Conf.LOG_CAT_TAG_GERAL,
					"KeyHash:"
							+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
		}
	}

}
